<template>
  <div class="report-preview">
    <!-- 报表头部信息 -->
    <div class="report-header">
      <div class="report-info">
        <h2 class="report-title">{{ report.title || report.name }}</h2>
        <p class="report-description">{{ report.description }}</p>
        <div class="report-meta">
          <span class="meta-item">
            <el-icon><Calendar /></el-icon>
            生成时间: {{ currentTime }}
          </span>
          <span class="meta-item" v-if="dateRange && dateRange.length">
            <el-icon><DateRange /></el-icon>
            数据范围: {{ dateRange[0] }} 至 {{ dateRange[1] }}
          </span>
        </div>
      </div>
      <div class="report-actions">
        <el-button-group>
          <el-button @click="handleExport('pdf')">
            <el-icon><Document /></el-icon>
            导出PDF
          </el-button>
          <el-button @click="handleExport('excel')">
            <el-icon><Files /></el-icon>
            导出Excel
          </el-button>
          <el-button @click="handlePrint">
            <el-icon><Printer /></el-icon>
            打印
          </el-button>
        </el-button-group>
      </div>
    </div>

    <!-- 报表内容 -->
    <div class="report-content" ref="reportContentRef">
      <!-- 标准报表模板 -->
      <div v-if="isStandardReport">
        <component 
          :is="getReportComponent()" 
          :date-range="dateRange"
          :loading="loading"
        />
      </div>

      <!-- 自定义报表内容 -->
      <div v-else class="custom-report-content">
        <div v-if="reportData.length === 0" class="empty-state">
          <el-empty description="暂无数据" />
        </div>
        <div v-else>
          <!-- 数据表格 -->
          <el-table 
            :data="reportData" 
            border
            stripe
            class="report-table"
            v-loading="loading"
          >
            <el-table-column 
              v-for="column in reportColumns" 
              :key="column.prop"
              :prop="column.prop"
              :label="column.label"
              :width="column.width"
              :formatter="column.formatter"
            />
          </el-table>

          <!-- 图表展示 -->
          <div v-if="showChart" class="chart-section">
            <div class="chart-container" ref="chartRef"></div>
          </div>

          <!-- 统计汇总 -->
          <div v-if="summaryData" class="summary-section">
            <h3>数据汇总</h3>
            <el-row :gutter="20">
              <el-col 
                v-for="(item, index) in summaryData" 
                :key="index"
                :span="6"
              >
                <el-card class="summary-card">
                  <div class="summary-item">
                    <div class="summary-label">{{ item.label }}</div>
                    <div class="summary-value">{{ item.value }}</div>
                    <div class="summary-unit">{{ item.unit }}</div>
                  </div>
                </el-card>
              </el-col>
            </el-row>
          </div>
        </div>
      </div>
    </div>

    <!-- 报表页脚 -->
    <div class="report-footer">
      <div class="footer-info">
        <p>报表生成系统 - ShopPuls 用户行为分析平台</p>
        <p>生成时间: {{ currentTime }}</p>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, nextTick } from 'vue'
import { Calendar, DateRange, Document, Files, Printer } from '@element-plus/icons-vue'
import * as echarts from 'echarts'

// 导入标准报表组件
import UserOverviewReport from './templates/UserOverviewReport.vue'
import UserBehaviorReport from './templates/UserBehaviorReport.vue'
import SalesSummaryReport from './templates/SalesSummaryReport.vue'
import ProductAnalysisReport from './templates/ProductAnalysisReport.vue'
import OperationKpiReport from './templates/OperationKpiReport.vue'

// Props
const props = defineProps({
  report: {
    type: Object,
    required: true
  },
  dateRange: {
    type: Array,
    default: () => []
  }
})

// Emits
const emit = defineEmits(['export'])

// 响应式数据
const loading = ref(false)
const reportContentRef = ref(null)
const chartRef = ref(null)
const currentTime = ref('')

// 模拟报表数据
const reportData = ref([])
const reportColumns = ref([])
const summaryData = ref(null)
const showChart = ref(false)

// 计算属性
const isStandardReport = computed(() => {
  return props.report.template && props.report.template !== 'custom'
})

// 方法
const getReportComponent = () => {
  const componentMap = {
    'user-overview': UserOverviewReport,
    'user-behavior': UserBehaviorReport,
    'sales-summary': SalesSummaryReport,
    'product-analysis': ProductAnalysisReport,
    'operation-kpi': OperationKpiReport
  }
  return componentMap[props.report.template] || 'div'
}

const handleExport = (format) => {
  emit('export', format)
}

const handlePrint = () => {
  window.print()
}

const loadReportData = async () => {
  if (isStandardReport.value) {
    return // 标准报表由子组件处理数据
  }

  loading.value = true
  try {
    // 模拟API调用获取自定义报表数据
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    // 模拟数据
    reportData.value = [
      { date: '2024-01-01', users: 1200, orders: 450, revenue: 25600 },
      { date: '2024-01-02', users: 1350, orders: 520, revenue: 28900 },
      { date: '2024-01-03', users: 1180, orders: 380, revenue: 22100 },
      { date: '2024-01-04', users: 1420, orders: 610, revenue: 31200 },
      { date: '2024-01-05', users: 1290, orders: 490, revenue: 27800 }
    ]

    reportColumns.value = [
      { prop: 'date', label: '日期', width: 120 },
      { prop: 'users', label: '用户数', width: 100 },
      { prop: 'orders', label: '订单数', width: 100 },
      { 
        prop: 'revenue', 
        label: '收入(元)', 
        width: 120,
        formatter: (row) => `¥${row.revenue.toLocaleString()}`
      }
    ]

    summaryData.value = [
      { label: '总用户数', value: '6,440', unit: '人' },
      { label: '总订单数', value: '2,450', unit: '单' },
      { label: '总收入', value: '135,600', unit: '元' },
      { label: '平均客单价', value: '55.3', unit: '元' }
    ]

    showChart.value = true
    
    // 渲染图表
    nextTick(() => {
      renderChart()
    })
  } catch (error) {
    console.error('加载报表数据失败:', error)
  } finally {
    loading.value = false
  }
}

const renderChart = () => {
  if (!chartRef.value) return

  const chart = echarts.init(chartRef.value)
  
  const option = {
    title: {
      text: '数据趋势图',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: ['用户数', '订单数', '收入'],
      top: 30
    },
    xAxis: {
      type: 'category',
      data: reportData.value.map(item => item.date)
    },
    yAxis: [
      {
        type: 'value',
        name: '数量',
        position: 'left'
      },
      {
        type: 'value',
        name: '收入(元)',
        position: 'right'
      }
    ],
    series: [
      {
        name: '用户数',
        type: 'line',
        data: reportData.value.map(item => item.users),
        yAxisIndex: 0
      },
      {
        name: '订单数',
        type: 'line',
        data: reportData.value.map(item => item.orders),
        yAxisIndex: 0
      },
      {
        name: '收入',
        type: 'bar',
        data: reportData.value.map(item => item.revenue),
        yAxisIndex: 1
      }
    ]
  }

  chart.setOption(option)
  
  // 响应式调整
  window.addEventListener('resize', () => {
    chart.resize()
  })
}

const updateCurrentTime = () => {
  currentTime.value = new Date().toLocaleString()
}

// 生命周期
onMounted(() => {
  updateCurrentTime()
  loadReportData()
})
</script>

<style scoped>
.report-preview {
  background: white;
  min-height: 600px;
}

.report-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  padding: 20px;
  border-bottom: 1px solid #e6e8eb;
  margin-bottom: 20px;
}

.report-title {
  margin: 0 0 8px 0;
  font-size: 20px;
  color: #303133;
}

.report-description {
  margin: 0 0 12px 0;
  color: #606266;
  font-size: 14px;
}

.report-meta {
  display: flex;
  gap: 20px;
  font-size: 12px;
  color: #909399;
}

.meta-item {
  display: flex;
  align-items: center;
  gap: 4px;
}

.report-content {
  padding: 0 20px;
  min-height: 400px;
}

.custom-report-content {
  margin-bottom: 20px;
}

.report-table {
  margin-bottom: 20px;
}

.chart-section {
  margin: 20px 0;
}

.chart-container {
  height: 400px;
  width: 100%;
}

.summary-section {
  margin-top: 20px;
}

.summary-section h3 {
  margin: 0 0 16px 0;
  font-size: 16px;
  color: #303133;
}

.summary-card {
  text-align: center;
}

.summary-item {
  padding: 10px;
}

.summary-label {
  font-size: 12px;
  color: #909399;
  margin-bottom: 4px;
}

.summary-value {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 4px;
}

.summary-unit {
  font-size: 12px;
  color: #606266;
}

.report-footer {
  border-top: 1px solid #e6e8eb;
  padding: 20px;
  text-align: center;
  color: #909399;
  font-size: 12px;
}

.footer-info p {
  margin: 4px 0;
}

.empty-state {
  text-align: center;
  padding: 60px 0;
}

/* 打印样式 */
@media print {
  .report-actions {
    display: none !important;
  }
  
  .report-preview {
    box-shadow: none !important;
    border: none !important;
  }
}
</style>
